<?php

require FCPATH . '/application/controllers/frontend.php';

class Project extends Frontend {

	public function __construct() {
		parent::__construct();
	}

	public function index() {
		$category = intval($this->uri->segment(3));
		$this->load_css('frontend_project_index');
		$this->set_js('CATEGORY', $category);
		$this->load_js(array('lib', 'frontend_project_index'));
		$this->rend('project_index');
	}

	public function show() {
		$this->load_css('frontend_project_show');
		$this->load_js(array('lib', 'frontend_project_show'));
		$this->load->model(array('project_model', 'node_model'));

		$lang = $this->get_language();
		$id = intval($this->uri->segment(3));

		$position = $this->project_model->total(array(array('where', 'id <', $id)));
		if($position > 0){
			$prevRecords = $this->project_model->records(array('id'), array(), array(), 1, $position - 1);
			$prevId = $prevRecords[0]->id;
		}else{
			$prevId = 0;
		}
		
		$nextRecords = $this->project_model->records(array('id'), array(), array(), 1, $position + 1);
		$nextId = isset($nextRecords[0]) ? $nextRecords[0]->id : 0;

		$columns = array('id', 'images', array('name_' . $lang, 'name'), array('description_' . $lang, 'description'));
		$records = $this->project_model->records($columns, array(array('where', 'id', $id)), array(), 1);

		if (isset($records[0])) {
			$imageIds = explode(',', $records[0]->images);
			$imageConditions = array(array('where_in', 'id', $imageIds));
			$this->rend('project_show', array(
				'project' => $records[0],
				'prev' => $prevId,
				'next' => $nextId,
				'images' => $this->node_model->records(array(), $imageConditions)
			));
		} else {
			die('404');
		}
	}

	public function records() {
		$lang = $this->get_language();
		$this->load->model('project_model');

		$category = intval($this->input->get('category'));
		$conditions = array();
		if ($category) {
			$conditions[] = array('like', 'category', ".$category.");
		}

		$data = array(
			'total' => $this->project_model->total($conditions),
			'records' => $this->project_model->rand($lang, $category, array(), 16)
		);
		$this->json_back('XT001', '', $data);
	}

	public function rand() {
		$this->load->model('project_model');
		$ids = $this->input->get('ids');
		$category = intval($this->input->get('category'));

		$project = $this->project_model->rand($this->get_language(), $category, $ids, 8);

		$this->json_back('XT001', '', $project ? $project : array());
	}

}